package utils

import (
	"fmt"
	"reflect"
	"time"
)

var (
	REFLECT_TYPE_TIME = reflect.TypeOf(time.Now())
)

func GetObjectFieldNameByTag(obj interface{}, tagfield string, matchvals ...string) string {
	v := reflect.ValueOf(obj)
	vk := v.Kind()
	if vk != reflect.Ptr {
		return ""
	}

	elem := v.Elem()
	vtype := elem.Type()
	for i := 0; i < elem.NumField(); i++ {
		fd := vtype.Field(i)
		str := fd.Tag.Get(tagfield)
		if len(str) == 0 {
			continue
		}

		idx := StrIndex(str, matchvals...)
		if idx == -1 {
			continue
		}
		return fd.Name
	}
	return ""
}

func GetObjectVal(obj interface{}, fieldname string, defval interface{}) interface{} {
	v := reflect.ValueOf(obj)
	vk := v.Kind()
	if vk != reflect.Ptr {
		return defval
	}

	elem := v.Elem()
	itm := elem.FieldByName(fieldname)

	if !itm.IsValid() {
		return defval
	}

	return itm.Interface()
}

func SetObjectVal(obj interface{}, fieldname string, val interface{}) error {
	v := reflect.ValueOf(obj)
	vk := v.Kind()
	if vk != reflect.Ptr {
		return fmt.Errorf("obj必须为结构体指针")
	}

	elem := v.Elem()
	itm := elem.FieldByName(fieldname)

	if !itm.IsValid() {
		return fmt.Errorf("obj找不对对应的字段[%s]", fieldname)
	}
	itm.Set(reflect.ValueOf(val))
	return nil
}
